package com.example.medicalapp.fragment;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import com.example.medicalapp.R;
import com.example.medicalapp.activity.DoctorAuthActivity;
import com.example.medicalapp.helper.DatabaseHelper;
import com.example.medicalapp.model.User;
import com.example.medicalapp.util.ValidationUtil;

public class DoctorRegisterFragment extends Fragment {
    private static final String TAG = "DoctorRegisterFragment";
    private EditText etUsername;
    private EditText etDoctorNumber;
    private EditText etPassword;
    private EditText etConfirmPassword;
    private EditText etEmail;
    private Button btnRegister;
    private DatabaseHelper dbHelper;

    // 创建Fragment实例的静态方法
    public static DoctorRegisterFragment newInstance() {
        return new DoctorRegisterFragment();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(TAG, "onCreate called");

        // 初始化数据库帮助类
        if (getActivity() != null) {
            dbHelper = new DatabaseHelper(getActivity());
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_register_doctor, container, false);

        // 初始化视图
        initViews(view);

        // 设置点击监听器
        setupListeners();

        return view;
    }

    private void initViews(View view) {
        etUsername = view.findViewById(R.id.et_username);
        etDoctorNumber = view.findViewById(R.id.et_doctor_number);
        etPassword = view.findViewById(R.id.et_password);
        etConfirmPassword = view.findViewById(R.id.et_confirm_password);
        etEmail = view.findViewById(R.id.et_email);
        btnRegister = view.findViewById(R.id.btn_register);
        Log.d(TAG, "Views initialized");
    }

    private void setupListeners() {
        btnRegister.setOnClickListener(v -> attemptRegister());
    }

    private void attemptRegister() {
        // 获取输入内容
        String username = etUsername.getText().toString().trim();
        String doctorNumber = etDoctorNumber.getText().toString().trim();
        String password = etPassword.getText().toString().trim();
        String confirmPassword = etConfirmPassword.getText().toString().trim();
        String email = etEmail.getText().toString().trim();

        // 验证输入
        if (username.isEmpty()) {
            etUsername.setError("请输入用户名");
            etUsername.requestFocus();
            return;
        }

        if (doctorNumber.isEmpty()) {
            etDoctorNumber.setError("请输入工号");
            etDoctorNumber.requestFocus();
            return;
        }

        if (!ValidationUtil.isValidPassword(password)) {
            etPassword.setError("密码长度至少6位");
            etPassword.requestFocus();
            return;
        }

        if (!password.equals(confirmPassword)) {
            etConfirmPassword.setError("两次输入的密码不一致");
            etConfirmPassword.requestFocus();
            return;
        }

        if (!ValidationUtil.isValidEmail(email)) {
            etEmail.setError("请输入有效的邮箱地址");
            etEmail.requestFocus();
            return;
        }

        Log.d(TAG, "Attempting doctor registration with username: " + username + ", doctor ID: " + doctorNumber);

        // 创建用户对象（角色为医生）
        User user = new User(username, password, email, "doctor", doctorNumber);

        // 插入数据库
        long result = dbHelper.addUser(user);

        if (result != -1) {
            // 注册成功
            Toast.makeText(getActivity(), "注册成功，请登录", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Doctor registered successfully with id: " + result);

            // 清空输入框
            clearInputFields();

            // 切换到登录标签页
            if (getActivity() instanceof DoctorAuthActivity) {
                ViewPager2 viewPager = getActivity().findViewById(R.id.view_pager);
                if (viewPager != null) {
                    viewPager.setCurrentItem(0); // 0表示登录标签页
                }
            }
        } else {
            // 注册失败（通常是用户名已存在）
            Toast.makeText(getActivity(), "注册失败，用户名可能已存在", Toast.LENGTH_SHORT).show();
            Log.d(TAG, "Doctor registration failed");
        }
    }

    // 清空输入框
    private void clearInputFields() {
        etUsername.setText("");
        etDoctorNumber.setText("");
        etPassword.setText("");
        etConfirmPassword.setText("");
        etEmail.setText("");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 关闭数据库连接
        if (dbHelper != null) {
            dbHelper.close();
        }
    }
}
